<?php
/**
 * Created by PhpStorm.
 * User: PC
 * Date: 2019/3/26
 * Time: 11:25
 */

namespace App\Api\V1\Services\Boilerplate;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Api\V1\Exceptions\Boilerplate\UserException;
use App\Exceptions\BaseException;
use App\Repositories\Boilerplate\UserRepository;
use Auth;
use Tymon\JWTAuth\Exceptions\JWTException;

class UserService
{
    protected $repository;

    public function __construct(UserRepository $userRepository)
    {
        $this->repository = $userRepository;
    }

    public function getList()
    {
//        throw new UserException(1120001);
        return $this->repository->all();
    }

    /**
     * CMF密码加密方法
     * @param string $pw 要加密的原始密码
     * @param string $authCode 加密字符串
     * @return string
     */
    protected function cmf_password($pw, $authCode = '')
    {
        if (empty($authCode)) {
            $authCode = env('DB_AUTHCODE');
        }
        $result = "###" . md5(md5($authCode . $pw));
        return $result;
    }

    /**
     * CMF密码加密方法 (X2.0.0以前的方法)
     * @param string $pw 要加密的原始密码
     * @return string
     */
    protected function cmf_password_old($pw)
    {
        $prefix = env('DB_PREFIX');
        $decor = md5($prefix);
        $mi = md5($pw);
        return substr($decor, 0, 12) . $mi . substr($decor, -4, 4);
    }

    /**
     * CMF密码比较方法,所有涉及密码比较的地方都用这个方法
     * @param string $password 要比较的密码
     * @param string $passwordInDb 数据库保存的已经加密过的密码
     * @return boolean 密码相同，返回true
     */
    protected function cmf_compare_password($password, $passwordInDb)
    {
        if (strpos($passwordInDb, "###") === 0) {
            return $this->cmf_password($password) == $passwordInDb;
        } else {
            return $this->cmf_password_old($password) == $passwordInDb;
        }
    }
    
    /**
     * @param array $credentials
     *
     * @return array
     * @throws \Exception
     */
    public function doLogin(array $credentials)
    {
        $password = $credentials["password"];
        if (strpos($credentials["username"], "@") > 0) {//邮箱登陆
            $user = $this->repository->findBy("email", $credentials["username"]);
        } else {
            $user = $this->repository->findBy("name", $credentials["username"]);
        }
        if (!$user) {
            throw new UserException(1120005);
        }
    
        if (!Hash::check($password, $user['password'])) { //密码不一致
            throw new UserException(1120006);
        }
    
        $token = JWTAuth::fromUser($user);
    
        return [
            'status'     => 'ok',
            'token'      => $token,
            'expires_in' => Auth::guard()->factory()->getTTL() * 60
        ];
    }

}